package com.cw.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cw.common.Constants;
import com.cw.common.R;
import com.cw.config.JwtConfig;
import com.cw.entity.*;
import com.cw.entity.dto.SetmealDto;
import com.cw.service.CategoryService;
import com.cw.service.DishService;
import com.cw.service.SetmealDishService;
import com.cw.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 添加保存套餐
     * @return
     */
    @PostMapping
    public R save(@RequestBody SetmealDto setmealDto, HttpServletRequest request) {
        if (!JwtConfig.getCurrentId(request).equals(Constants.ADMIN_ID)){
            Employee emp=(Employee)this.redisTemplate.opsForValue().get("EMP:"+JwtConfig.getCurrentId(request));
            setmealDto.setWindowsId(emp.getWindowId());
        }
        log.info("保存的数据为：{}",setmealDto);
        setmealService.saveWithDish(setmealDto);

        return R.success("添加成功");
    }

    /**
     * 套餐分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R page(Integer page,Integer pageSize, String name, HttpServletRequest request){
        //1.获取数据log.info("获取的分页信息：{}，大小{}，搜索的名字，{}",page,pageSize,name);

        //2.分页查询
        Page<Setmeal> setmealPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name!=null,Setmeal::getName,name);
        if (!JwtConfig.getCurrentId(request).equals(Constants.ADMIN_ID)){
            Employee emp=(Employee)this.redisTemplate.opsForHash().get("EMP",JwtConfig.getCurrentId(request));
           wrapper.eq(emp!=null,Setmeal::getWindowsId,emp.getWindowId());
        }
        setmealService.page(setmealPage,wrapper);

        //3.分类名称转移
        Page<SetmealDto> setmealDtoPage = new Page<>(page,pageSize);
        //3.1基本数据拷贝
        BeanUtils.copyProperties(setmealPage,setmealDtoPage,"records");

        //4.解决套餐分类为空问题
        List<SetmealDto> list = setmealPage.getRecords().stream().map(item -> {
            SetmealDto setmealDto = new SetmealDto();

            //4.1套餐数据拷贝
            BeanUtils.copyProperties(item, setmealDto);
            //4.2通过原有属性获取分类id
            Long categoryId = item.getCategoryId();


            Category category = categoryService.getById(categoryId);
            String name1 = category.getName();

            setmealDto.setCategoryName(name1);

            return setmealDto;
        }).collect(Collectors.toList());


        setmealDtoPage.setRecords(list);

        return R.success(setmealDtoPage);
    }

    /**
     * 批量删除套餐
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value="setmealCache",allEntries = true)//清除setmealCache名称下，所有的缓存数据
    public R delete(@RequestParam List<Long> ids){
        log.info("要删除的套餐：{}",ids);
        setmealService.deleteById(ids);
        return  R.success("null");
    }

    /**
     * 套餐修改
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public  R update(@PathVariable Long id){
        //获取数据
    log.info("查询到的内容是：{}",id);
        Setmeal setmeal = setmealService.getById(id);

        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SetmealDish::getSetmealId,id);
        List<SetmealDish> list = setmealDishService.list(wrapper);

        //把基本属性添加到Dto集合中
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal,setmealDto);


        //把菜品添加到套餐分类中
        setmealDto.setSetmealDishes(list);

//        SetmealDto dto = new SetmealDto();
//        //拷贝基本参数


        return   R.success(setmealDto);
    }

    /**
     * 保存套餐的修改
     * @param setmealDto
     * @return
     */
    @PutMapping
    public  R  saveThePackage(@RequestBody SetmealDto setmealDto){
        log.info("收集到的套餐数据是：{}",setmealDto);
        //1.修改套餐基本数据
        setmealService.updateById(setmealDto);

        List<SetmealDish> dishList = setmealDto.getSetmealDishes();

        //删除套餐内的所有菜品
        //delete from setmealDishes where setmeal_dish = ?
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(setmealDto.getId()!=null,SetmealDish::getSetmealId,setmealDto.getId());
        setmealDishService.remove(wrapper);

        //把每一个菜品重新添加到数据库
//        dishList.stream().map(item->{
        //insert into ...where setmealDto.getId = SetmealDish::getSetmealId
        List<SetmealDish> list = dishList.stream().map(item -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());

        setmealDishService.saveBatch(list);

        return  R.success("修改成功");
    }


    /**
     * 套餐批量起售，停售
     * @param id
     * @param ids
     * @return
     */
    @PostMapping("/status/{id}")
    public R updateBatch(@PathVariable Integer id,@RequestParam List<Long> ids){
        //根据id查询出所有选择的套餐

        List<Setmeal> setmeals = setmealService.listByIds(ids);

        List<Setmeal> list = setmeals.stream().map(item -> {
            item.setStatus(id);
            setmealService.updateById(item);
            return item;
        }).collect(Collectors.toList());

        return  R.success(list);

    }


    @GetMapping("/list")
    public R list(@RequestParam(value = "categoryId") String categoryId,@RequestParam(value = "status") Integer status ){
        List<Setmeal> list;
        if (redisTemplate.opsForValue().get(categoryId)==null){
            LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Setmeal::getStatus,status);
            wrapper.eq(Setmeal::getCategoryId,categoryId);
            //查询
            list = setmealService.list(wrapper);
            this.redisTemplate.opsForValue().set("category_"+categoryId,list);
        }else{
            list= (List<Setmeal>) this.redisTemplate.opsForValue().get("category_"+categoryId);
        }
        return R.success(list);
    }


    /**
     * 菜品，套餐，点击显示
     * @return id = 套餐的id
     */
    @GetMapping("/dish/{id}")
    public R dish(@PathVariable Long id){
        //1.获取参数
        log.info("菜品id为：{}",id);


        //2.查询套餐内容
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        //找到套菜对应的菜品
        wrapper.eq(id!=null,SetmealDish::getSetmealId,id);
        //3.获取套餐菜品的对象
        List<SetmealDish> list = setmealDishService.list(wrapper);

        //4.图片解决
        list = list.stream().map(item -> {
            //item:每个菜品
            Dish dish = dishService.getById(item.getDishId());
            BeanUtils.copyProperties(dish,item);
            return item;
        }).collect(Collectors.toList());


        return  R.success(list);
    }

}
